package NoLock.Atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

import static ProcessThread.util.Sleeper.sleep;


@Slf4j(topic = "c.AtomicMarkableReference_")
public class AtomicMarkableReference_ {
    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag = new GarbageBag("装满了垃圾");
        // 参数2 mark 可以看作一个标记，表示垃圾袋满了
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);


        GarbageBag prev = ref.getReference();//就是bag对象
        log.debug("主人检查 {}",prev);

        new Thread(() -> {
            log.debug("bag和prev的hashcode比较 {} == {}",bag.hashCode(),prev.hashCode());
            log.debug("保姆检查 {}",bag);
            bag.setDesc("保姆倒垃圾");
            ref.compareAndSet(bag, bag, true, false);
            bag.setDesc("空垃圾袋");
            log.debug("保姆更换 {} ",bag);
        },"保洁阿姨").start();

        sleep(1);
        log.debug("主人检查 {} 想换一个新的",bag);
        boolean success = ref.compareAndSet(prev, new GarbageBag("新垃圾袋"), true, false);
        log.debug("换了么？" + success);
    }
}

class GarbageBag {
    String desc;

    public GarbageBag(String desc) {
        this.desc = desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return super.toString() + " " + desc;
    }
}